﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Universum.Model.Domain.Classes;
using Universum.Infrastructure.Persistence;
using Universum.Infrastructure.Persistence.Queries.Classes;
using System.Security.Principal;
using Universum.Model.Services.Indexing;
using System.Text;

namespace Universum.Model.Services.Classes
{
	public class PageArticleServiceImpl : IPageArticleService
	{

		IRepository _Repository;
		IPrincipal _Principal;
		ITeacherArticleIndexingService _PageArticleIndexingService;
		IFriendlyUrlService _FriendlyUrlService;
		public PageArticleServiceImpl( IRepository repository, IPrincipal 
			principal,
			ITeacherArticleIndexingService pageArticleIndexingService,
			IFriendlyUrlService friendlyUrl
			)
		{
			_Principal = principal;
			_Repository = repository;
			_FriendlyUrlService = friendlyUrl;
			_PageArticleIndexingService = pageArticleIndexingService;
		}
		#region IPageArticleService Members

		public IList<PageArticle> GetArticlesByPageGroupId(Guid guid)
		{
			return _Repository.Query(new PageArticleByPageGroupId(guid))
				.OrderBy(it => it.Publish)
				.ToList();
		}

		#endregion

		#region IPageArticleService Members


		public PageArticle CreateNew()
		{
			return new PageArticle
			{
				Username = _Principal.Identity.Name,
				Created = DateTime.Now,
				ID = Guid.NewGuid(),
				
			};
		}

		public void SaveOrUpdate(PageArticle newArticle)
		{
			var sb = new StringBuilder(newArticle.ID.ToInt().ToString())
			.Append('-').Append(newArticle.Title);
			newArticle.Slug = _FriendlyUrlService.CreateSlugFrom(
				sb.ToString());
			_Repository.SaveOrUpdate(newArticle);
			_PageArticleIndexingService.Update(newArticle);
		}

		public PageArticle GetArticleBySlug(string slug)
		{
			return _Repository.Query(new PageArticleBySlug(slug))
				
				.FirstOrDefault()
				;
		}

		public PageArticle GetArticleById(Guid guid)
		{
			return _Repository.Load<PageArticle>(guid);
		}

		
		public void Remove(PageArticle entity)
		{
			_Repository.Remove(entity);
			_PageArticleIndexingService.Remove(entity);
		}

		#endregion

		#region IPageArticleService Members


		public void RemoveByPageGroupId(Guid pageGroupId)
		{
			var articles = _Repository.Query(
					new PageArticleByPageGroupId(pageGroupId));
			foreach (var article in articles)
			{
				_Repository.Remove(article);
				_PageArticleIndexingService.Remove(article);
			}
		}

		#endregion

		#region IPageArticleService Members


		public IList<PageArticle> GetPublishedArticlesByPageGroupId(Guid guid)
		{
			return _Repository.Query(new PageArticleByPageGroupId(guid))
				.Where(it=>it.Publish <= DateTime.Now)
				.OrderBy(it => it.Publish)
				.ToList();
		}

		#endregion
	}
}
